/**
 * PackDataMonitorAction.java
 * Created at 2017-2-2
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.monitor.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.DateUtils;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.StrUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.monitor.model.FenceGpsInfo;
import com.broadtext.rms.monitor.model.PackLocationInfo;
import com.broadtext.rms.monitor.model.TtPack;
import com.broadtext.rms.monitor.model.TtPackCurrent;
import com.broadtext.rms.monitor.service.IPackDataMonitorService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: PackDataMonitorAction
 * </p>
 * <p>
 * Description: 电池数据监控控制层
 * </p>
 * <p>
 * Author: shihui
 * </p>
 * <p>
 * Date: 2017-2-20
 * </p>
 */
@Controller
@RequestMapping("/main/packDataMonitor")
public class PackDataMonitorAction {

    /**
     * 日志信息
     */
    public static Logger logger = LoggerFactory.getLogger(TtPack.class);

    /**
     * 电池监控服务类
     */
    @Autowired
    @Qualifier("packDataMonitorService")
    private IPackDataMonitorService packDataMonitorService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;

    /**
     * 
     * <p>
     * Description: 查询电池数据列表
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/getPackDataList.mvc")
    @ResponseBody
    public void getPackDataList(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            //判断当前登录人是否是客户账号，进行数据过滤
            Map<String, Object> checkMap;
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //该用户是客户账号
                map.put("cusId", checkMap.get("cusId"));
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<Object> pageBean;
            pageBean = this.packDataMonitorService.findPackMonitor(map, pageBounds);
            Map dataMap;
            dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException | DaoException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * <p>
     * Description: 检查待报废电池状态是否包含报废、有效状态
     * </p>
     * 
     * @param pkId 主键id
     * @return 检查结果 true 可以无效， false 不可无效
     * @throws DaoException 异常
     */
    @RequestMapping(value = "checkEnableStatus.mvc")
    @ResponseBody
    public Object checkEnableStatus(String pkId){
        //存储主键id
        String[] ids;
        ids = pkId.split(",");
        try {
            return this.packDataMonitorService.checkEnableStatus(ids);
        } catch (Exception e) {
            logger.error("查询出错：", e);
        }
        return null;
    }

    /**
     * 
     * <p>
     * Description: 设置无效
     * </p>
     * 
     * @param request 请求
     * @param packId 电池ID
     * @return 设置结果
     */
    @RequestMapping("/setPackUnenable.mvc")
    @ResponseBody
    public Map<String, Object> setPackUnenable(HttpServletRequest request, String packId) {
        String[] packIdArray;
        packIdArray = packId.split(",");

        Map<String, Object> map;
        map = new HashMap<String, Object>();

        Map<String, Object> parMap;
        parMap = new HashMap<String, Object>();
        try {
            parMap.put("sysName", String.valueOf(request.getSession().getAttribute("sys.userName")));
            map = this.packDataMonitorService.setPackUnenable(packIdArray, parMap);
        } catch (ServiceException e) {
            logger.error("查询出错：", e);
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 
     * <p>
     * Description: 获取监控电池详情
     * </p>
     * 
     * @param t 查询条件
     * @return 详情map集
     * @throws DaoException 异常
     */
    @RequestMapping("/getPackDataDetail.mvc")
    @ResponseBody
    public Object getMonitorDataInfo(TtPackCurrent t) {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        //监控电池实时采集数据
        Map<String, Object> tt;
        try {
            tt = this.packDataMonitorService.getMonitorDataInfoCurrent(t);
            dataMap.put("packInfo", tt);
        } catch (DaoException e) {
            logger.error("查询出错：", e);
            e.printStackTrace();
        }
        
        return dataMap;
    }

    /**
     * 
     * <p>
     * Description: 获取图表信息
     * </p>
     * 
     * @param t 查询条件
     * @param client 终端id
     * @param packCode 电池id
     * @param maxVol 最高电压
     * @param minVol 最低电压
     * @return 详情map集
     * @throws DaoException 异常
     */
    @RequestMapping("/getEchartData.mvc")
    @ResponseBody
    public Object getEchartData(TtPackCurrent t,@RequestParam("clientId") String clientId, @RequestParam("packCode") String packCode,
            @RequestParam("maxVol")String maxVol, @RequestParam("minVol") String minVol){
        //参数
        Map<String, Object> paramsMap;
        paramsMap = new HashMap<String, Object>();
        paramsMap.put("clientId", clientId);
        paramsMap.put("packCode", packCode);
        paramsMap.put("maxVol", maxVol);
        paramsMap.put("minVol", minVol);
        //结果
        try {
            return this.packDataMonitorService.getPackChartInfo(paramsMap);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * <p>
     * Description: 检查待报废电池状态是否包含报废
     * </p>
     * 
     * @param pkId 主键id
     * @return 检查结果 true 可以报废， false 不可报废
     * @throws DaoException 异常
     */
    @RequestMapping(value = "checkFailureStatus.mvc")
    @ResponseBody
    public Object checkFailureStatus(String pkId){
        //存储主键id
        String[] ids;
        ids = pkId.split(",");
        try {
            return this.packDataMonitorService.checkFailureStatus(ids);
        } catch (DaoException e) {
            logger.error("检查待报废电池状态是否包含报废出错：", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * <p>
     * Description: 报废电池
     * </p>
     * @param request 请求
     * @param pkId 主键id
     * @return 操作结果
     * @throws DaoException 异常
     */
    @RequestMapping(value = "setFailure.mvc")
    @ResponseBody
    public Object setFailure(HttpServletRequest request, String pkId){
        String result = "";
        try {
            String currentUser;
            currentUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
            //存储主键id
            String[] ids;
            ids = pkId.split(",");
            this.packDataMonitorService.setFailure(ids, currentUser);
            result = "success";
        } catch (DaoException e) {
            logger.error("报废电池出错：", e);
            e.printStackTrace();
            result = "false";
        }
        return result;
    }

    /**
     * 
     * <p>
     * Description: 获取监控电池当前位置信息
     * </p>
     * 
     * @param c 终端id
     * @param p 电池唯一序列号
     * @return 监控电池当前位置信息
     */
    @RequestMapping(value = "getCurrentLocationInfo.mvc")
    @ResponseBody
    public PackLocationInfo getCurrentLocationInfo(@RequestParam("clientId") String c,
            @RequestParam("packCode") String p) {
        PackLocationInfo l;
        l = new PackLocationInfo();
        try {
            l = this.packDataMonitorService.findCurrentLocationInfo(c, p);
        } catch (DaoException e) {
            e.printStackTrace();
            logger.error("获取电池位置信息出错：", e);
        }
        return l;
    }

    /**
     * 
     * <p>
     * Description: 获取历史位置列表
     * </p>
     * 
     * @param request 请求
     * @return 结果集
     * @throws DaoException 异常
     */
    @RequestMapping(value = "getHistoryLocationList.mvc")
    @ResponseBody
    public Object getHistoryLocationList(@RequestParam("clientId") String clientId,
            @RequestParam("packCode") String packCode, @RequestParam("gatherTimes")String gatherTimes,
            @RequestParam("selectTime") String selectTime, @RequestParam("flag")String flag) {
        //处理查询条件
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("clientId", clientId);
        map.put("packCode", packCode);
        map.put("gatherTimes", gatherTimes);
        try {
            if(StringUtils.isNotBlank(gatherTimes)){
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = f.parse(gatherTimes);
                String startTime = DateUtils.getOneHoursAgoTime(date);
                map.put("startTime", startTime);
            }else {
                map.put("startTime", DateUtils.getDayStartStr(new Date()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        map.put("selectTime", selectTime);
        map.put("flag", flag);
        //查询
        List<PackLocationInfo> histtoryLocationList;
        histtoryLocationList = new ArrayList<PackLocationInfo>();
        try {
            histtoryLocationList = this.packDataMonitorService.findHistoryLocationList(map);
        } catch (DaoException e) {
            logger.error("获取历史位置列表出错：", e);
            e.printStackTrace();
        }
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        dataMap.put("aaData", histtoryLocationList);
        return dataMap;
    }

    /**
     * 
     * <p>
     * Description: 导出历史轨迹
     * </p>
     * 
     * @param c 终端id
     * @param p 电池唯一序列号
     * @param gatherTime 选择的日期
     * @param exportTime 导出时间
     * @param response 响应
     * @return 结果集
     */
    @RequestMapping(value = "getHistoryLocationListForTrail.mvc")
    public void getHistoryLocationListForTrail(@RequestParam("clientId") String c, @RequestParam("packCode") String p,
            @RequestParam("gatherTimes") String gatherTime, HttpServletResponse response,
            @RequestParam("exportTime") String exportTime) {
        //处理查询条件
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("clientId", c);
        map.put("packCode", p);
        map.put("gatherTimes", gatherTime);
        try {
            if(StringUtils.isNotBlank(gatherTime)){
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = f.parse(gatherTime);
                String startTime = DateUtils.getOneHoursAgoTime(date);
                map.put("startTime", startTime);
            }else {
                map.put("startTime", DateUtils.getDayStartStr(new Date()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        map.put("exportTime", exportTime);
        map.put("flag", "current");
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            this.packDataMonitorService.findHistoryLocationExportList(map, response);
        } catch (DaoException e) {
            logger.error("查询历史轨迹出错：", e);
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>
     * Description: 导出历史轨迹
     * </p>
     * 
     * @param c 终端id
     * @param p 电池唯一序列号
     * @param gatherTimes 选择的日期
     * @param exportTime 导出时间 唯一区别
     * @param response 响应
     * @return 结果集
     */
    @RequestMapping(value = "getHistoryLocationListForTrailTwo.mvc")
    public void getHistoryLocationListForTrailTwo(@RequestParam("clientId") String c,
            @RequestParam("packCode") String p, @RequestParam("gatherTimes") String gatherTime,
            @RequestParam("selectTime") String selectTime,@RequestParam("exportTime") String exportTime,
            HttpServletResponse response) {
        //处理查询条件
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        map.put("clientId", c);
        map.put("packCode", p);
        map.put("gatherTimes", gatherTime);
        map.put("selectTime", selectTime);
        map.put("flag", "history");
        map.put("exportTime", exportTime);
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            this.packDataMonitorService.findHistoryLocationExportList(map, response);
        } catch (DaoException e) {
            logger.error("查询历史轨迹出错：", e);
            e.printStackTrace();
        }
    }

    /**
     * 
     * <p>
     * Description: 查询历史报警列表
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/getHistoryWarningList.mvc")
    @ResponseBody
    public void getHistoryWarningList(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<Object> pageBean;
            pageBean = this.packDataMonitorService.findHistoryWarningList(map, pageBounds);
            Map dataMap;
            dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * <p>
     * Description: 查询电池监控历史数据
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/getMonitorHistoryDataList.mvc")
    @ResponseBody
    public void getMonitorHistoryDataList(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<Object> pageBean;
            pageBean = this.packDataMonitorService.findMonitorHistoryDataList(map, pageBounds);
            Map dataMap;
            dataMap = new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /**
     * o
     * <p>
     * Description: 获取监控电池历史详情
     * </p>
     * 
     * @param clientId 终端id
     * @param packCode 电池id
     * @param gatherTime 采集时间
     * @return 详情map集
     * @throws DaoException 异常
     */
    @RequestMapping("/getPackHistoryDataDetail.mvc")
    @ResponseBody
    public Object getPackHistoryDataDetail(@RequestParam("colClientId") String clientId,
            @RequestParam("packCode") String packCode, @RequestParam("gatherTime") String gatherTime)
            {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        Map<String, Object> queryMap;
        queryMap  = new HashMap<String, Object>();
        queryMap.put("colClientId", clientId);
        queryMap.put("packCode", packCode);
        queryMap.put("gatherTimes", gatherTime);
        //监控电池历史采集数据
        Map<String, Object> tt;
        try {
            tt = this.packDataMonitorService.findPackHistoryDataDetail(queryMap);
            dataMap.put("packInfo", tt);
        } catch (DaoException | ParseException e) {
            logger.error("获取监控电池历史详情出错：", e);
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: </p>
     * @param request 请求
     * @param pkId 告警记录ID
     * @return 下载
     * @throws IOException 异常
     */
    @RequestMapping(value = "dataBack.mvc")
    @ResponseBody
    public Map<String, Object> dataBack(HttpServletRequest request, HttpServletResponse response, String pkId)
        throws IOException {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String sysuser;
        sysuser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try {
            //数据回传
            map = this.packDataMonitorService.dataBackToZip(pkId, sysuser);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 下载报文</p>
     * @param request 请求
     * @param response 响应
     * @param pkId 告警ID
     */
    @RequestMapping(value = "downloadDatagram.mvc")
    @ResponseBody
    public void downloadDatagram (HttpServletRequest request, HttpServletResponse response, String pkId) {
        String path;
        try {
            path = this.packDataMonitorService.getAlertZipPath(pkId);
            // path是指欲下载的文件的路径。
            File file = new File(path);
            if (file.isFile()) {
                String filename = file.getName();
                InputStream fis = new BufferedInputStream(new FileInputStream(path));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream out = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                out.write(buffer);
                out.flush();
                out.close();
            } else {
                //文件或路径不存在
                logger.info("文件或路径不存在:" + path);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * <p>Description: 验证历史告警记录是否未处理</p>
     * @param request 请求
     * @param ids 告警记录ID
     * @return 验证结果
     */
    @RequestMapping(value = "checkUnhandled.mvc")
    @ResponseBody
    public Object checkUnhandled(HttpServletRequest request, String ids) {
        //存储主键id
        String[] idArray;
        idArray = ids.split(",");
        try {
            return this.packDataMonitorService.checkUnhandled(idArray);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 
     * <p>Description: 验证历史告警记录是否未处理</p>
     * @param request 请求
     * @param ids 告警记录ID
     * @return 验证结果
     */
    @RequestMapping(value = "checkUnneedhandled.mvc")
    @ResponseBody
    public Object checkUnneedhandled(HttpServletRequest request, String ids) {
        //存储主键id
        String[] idArray;
        idArray = ids.split(",");
        try {
            return this.packDataMonitorService.checkUnneedhandled(idArray);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 
     * <p>Description: 更新历史告警记录处理结果</p>
     * @param request 请求
     * @param ids 告警记录ID
     */
    @RequestMapping(value = "setAlertHandled.mvc")
    @ResponseBody
    public Map<String, Object> setAlertHandled(HttpServletRequest request, String ids, String handleType) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        //存储主键id
        String[] idArray;
        idArray = new String[]{};
        if (ids != null) {
            idArray = ids.split(",");
        }
        String sysuser;
        sysuser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try {
            map = this.packDataMonitorService.updateAlertHandled(idArray, handleType, sysuser);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>
     * Description: 获取监控电池历史数据 温度电压图表信息
     * </p>
     * 
     * @param clientId 终端id
     * @param packCode 电池idO
     * @param gatherTime 采集时间
     * @param maxVol 单体最高压
     * @param minVol 单体最低压
     * @return 详情map集
     * @throws DaoException 异常
     */
    @RequestMapping("/getEchartHistoryData.mvc")
    @ResponseBody
    public Object getEchartHistoryData(@RequestParam("colClientId") String clientId,
            @RequestParam("packCode") String packCode, @RequestParam("gatherTime") String gatherTime,
            @RequestParam("maxVol")String maxVol, @RequestParam("minVol") String minVol){
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        //查询条件
        Map<String, Object> queryMap;
        queryMap  = new HashMap<String, Object>();
        queryMap.put("colClientId", clientId);
        queryMap.put("packCode", packCode);
        queryMap.put("gatherTimes", gatherTime);
        queryMap.put("maxVol", maxVol);
        queryMap.put("minVol", minVol);
        //监控电池实时采集电压温度信息 每个map存一组电压跟电流信息
        List<Map<String, Object>> chartsInfo;
        chartsInfo = new ArrayList<Map<String, Object>>();
        try {
            chartsInfo = this.packDataMonitorService.findEchartHistoryData1(queryMap);
        } catch (DaoException e) {
            logger.error("获取监控电池历史数据出错：", e);
            e.printStackTrace();
        }
        dataMap.put("chartInfo", chartsInfo);
        return dataMap;
    }
    
    /**
     * 
     * <p>
     * Description: 电池历史数据  位置监控获取监控电池位置信息
     * </p>
     * 
     * @param clientId 终端id
     * @param packCode 电池id
     * @param gatherTime 采集时间
     * @return
     */
    @RequestMapping(value = "getHistoryLocationInfo.mvc")
    @ResponseBody
    public PackLocationInfo getHistoryLocationInfo(@RequestParam("colClientId") String clientId,
            @RequestParam("packCode") String packCode, @RequestParam("gatherTime") String gatherTime) {
        PackLocationInfo l;
        l = new PackLocationInfo();
        //查询条件
        Map<String, Object> queryMap;
        queryMap  = new HashMap<String, Object>();
        queryMap.put("colClientId", clientId);
        queryMap.put("packCode", packCode);
        queryMap.put("gatherTimes", gatherTime);
        try {
            l = this.packDataMonitorService.findHistoryLocationInfo(queryMap);
        } catch (Exception e) {
            logger.error("获取电池位置信息出错：", e);
            e.printStackTrace();
        }
        return l;
    }
    
    /**
     * 
     * <p>
     * Description: 查询历史轨迹列表
     * </p>
     * 
     * @param request 请求
     * @param response 响应
     * @throws DaoException 异常
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/getHistoryLocationListByPage.mvc")
    public void getHistoryLocationListByPage(HttpServletRequest request, HttpServletResponse response) throws ServiceException, DaoException {
        PageBounds pageBounds;
        pageBounds = new PageBounds();
        Map<String, Object> map;
        String aoData;
        aoData = request.getParameter("aoData");
        JSONArray array;
        array = JSON.parseArray(aoData);
        map = new HashMap<String, Object>();
        if (array != null) {
            Iterator it;
            it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        String gatherTimes = map.get("gatherTimes").toString();
        try {
            if(StringUtils.isNotBlank(gatherTimes)){
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = f.parse(gatherTimes);
                String startTime = DateUtils.getOneHoursAgoTime(date);
                map.put("startTime", startTime);
            }else {
                map.put("startTime", DateUtils.getDayStartStr(new Date()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        EntityPageBean<PackLocationInfo> pageBean;
        pageBean = this.packDataMonitorService.findHistoryLocationListByPage(map, pageBounds);
        Map dataMap;
        dataMap = new HashMap();
        dataMap.put("recordsTotal", pageBean.getiTotalRecords());
        dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
        dataMap.put("aaData", pageBean.getResults());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(JSON.toJSONString(dataMap));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    /**
     * 
     * <p>Description: 检查文件是否生成成功</p>
     * @param fileName 文件名
     * @return 判断结果
     */
    @RequestMapping("/checkExcelTempExist.mvc")
    @ResponseBody
    public Object checkExcelTempExist(@RequestParam("fileName")String fileName){
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        File file = new File("D:"+File.separator + "excelTemp" + File.separator + "导出历史轨迹"+fileName);
        if(file.exists()){
            //文件已经生成
            map.put("flag", "success");
        } else {
            map.put("flag", "fail");
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 检查文件是否生成成功</p>
     * @param fileName 文件名
     * @return 判断结果
     */
    @RequestMapping("/downloadTrailExcel.mvc")
    public void downloadTrailExcel(@RequestParam("fileName")String fileName, HttpServletResponse response){
        RmsUtil.download("导出历史轨迹"+fileName, "D:"+File.separator + "excelTemp" + File.separator, response);
        //删除临时文件
        File file = new File("D:"+File.separator + "excelTemp" + File.separator + "导出历史轨迹"+fileName);
        file.delete();
    }
    
    
    /**
     * 
     * <p>
     * Description: 检查电池掉电状态
     * </p>
     * 
     * @param packCode packCode
     * @param clientId clientId
     * @return 检查结果 true 可以无效， false 不可无效
     * @throws DaoException 异常
     */
    @RequestMapping(value = "checkPowerFailStatus.mvc")
    @ResponseBody
    public Object checkPowerFailStatus(@RequestParam("packCode")String packCode,
            @RequestParam("clientId")String clientId){
        try {
            Map<String, Object> params;
            params = new HashMap<String, Object>();
            params.put("packCode", packCode);
            params.put("clientId", clientId);
            return this.packDataMonitorService.checkPowerFailStatus(params);
        } catch (Exception e) {
            logger.error("查询出错：", e);
        }
        return null;
    }
    
    /**
     * 
     * <p>
     * Description: 检查电池掉电状态
     * </p>
     * 
     * @param packCode packCode
     * @param clientId clientId
     * @return 检查结果 true 可以无效， false 不可无效
     * @throws DaoException 异常
     */
    @RequestMapping(value = "checkPackStatus.mvc")
    @ResponseBody
    public Map<String,Object> checkPackStatus(@RequestParam("packCode")String packCode,
            @RequestParam("clientId")String clientId){
        try {
            Map<String, Object> params;
            params = new HashMap<String, Object>();
            params.put("packCode", packCode);
            params.put("clientId", clientId);
            return this.packDataMonitorService.checkPackState(params);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询出错：", e);
        }
        return null;
    }
    /**
     * 
     * <p>Description: 客户导入离线文件 </p>
     * @param files 文件
     * @param request 请求
     * @return 导入结果 返回信息
     */
    @RequestMapping(value = "/importFile.mvc")
    @ResponseBody
    public Object importFile(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        //返回值
        Map<String, Object> map;
        map = new HashMap<String, Object>();

        /*
         * 验证文件是否已经在上传过
         */
        List<String> fileNameLists = new ArrayList<String>();
        for (int i = 0; i < files.length; i++) {
            fileNameLists.add(files[i].getOriginalFilename());
        }
        try {
            if(!"success".equals(this.packDataMonitorService.checkOfflineFileExist(fileNameLists))){
                map.put("result", "该报文已经存在！");
                return map;
            }
        } catch (DaoException e1) {
            logger.error("检查离线文件是否存在出错：", e1);
            map.put("result", "出错了");
            return map;
        }
        
        /*
         * 封装报文内容
         */
        List<String> dataList = new ArrayList<String>();
        for (int i = 0; i < files.length; i++) {
            List<String> dataTempList = new ArrayList<String>();
            if (!files[i].isEmpty()) {
                try {
                    //拿到上传文件的输入流  
                    ByteArrayInputStream ba = (ByteArrayInputStream) files[i].getInputStream();
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new InputStreamReader(ba));
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            dataTempList.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                                br = null;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            dataTempList = StrUtil.ListToString(dataTempList);
            dataList.addAll(dataTempList);
        }
        //调用wcf服务进行报文上传
        try {
            if(!"success".equals(this.packDataMonitorService.callWCFService(request, dataList, files))){
                map.put("result", "上传报文出错！");
            }else {
                map.put("result", "success");
            }
        } catch (DaoException e) {
            map.put("result", "上传报文出错！");
        }
        return map;
    }
    
    /**
     * 获取电子围栏信息
     * @param c 终端id
     * @param p 电池id
     * @return 电子围栏信息
     */
    @RequestMapping(value = "/getEfenceInfo.mvc")
    @ResponseBody
    public Object getEfenceInfo(@RequestParam("clientId") String c,
            @RequestParam("packCode") String p){
    	 //返回值
    	 Map<String, Object> dataMap = new HashMap<String, Object>();
    	 //围栏信息
    	 Map<String, Object> fenceMap = new HashMap<String, Object>();
    	 //电池当前位置信息
    	 PackLocationInfo l;
         l = new PackLocationInfo();
         try {
             l = this.packDataMonitorService.findCurrentLocationInfo(c, p);
             fenceMap = this.packDataMonitorService.getEfenceInfo(c, p);
         } catch (DaoException e) {
             logger.error("获取电池位置信息出错：", e);
         }
         dataMap.put("locationInfo", l);
         dataMap.put("fenceInfo", fenceMap);
         return dataMap;
    }
    
    /**
     * 保存电子围栏信息
     * @return 保存结果
     */
    @RequestMapping(value = "/saveEfenceInfo.mvc")
    @ResponseBody
    public Object saveEfenceInfo(HttpServletRequest request){
    	String ds = request.getParameter("data");
    	JSONArray json = JSONArray.parseArray(ds);
    	JSONObject jsonOne;
    	List<FenceGpsInfo> dataList = new ArrayList<FenceGpsInfo>();
    	for (int i = 0; i < json.size(); i++) {
    		jsonOne = json.getJSONObject(i);
    		FenceGpsInfo o = new FenceGpsInfo();
    		o.setDelFlag("0");
    		o.setPkId(UUIDUtils.getUUID());
    		o.setCreateDate(new Date());
    		if(jsonOne.get("no")!=null&&!StrUtil.isEmpty(jsonOne.get("no").toString())){
    		    o.setNo(Float.parseFloat(jsonOne.get("no").toString()));
    		}
    		o.setCreateUser("sys");
    		o.setLon(jsonOne.get("lon").toString());
    		o.setLat(jsonOne.get("lat").toString());
    		o.setColClientId(jsonOne.get("colClientId").toString());
    		o.setPackCode(jsonOne.get("packCode").toString());
    		o.setType(jsonOne.get("type").toString());
    		if(jsonOne.get("radius")!=null&&!StrUtil.isEmpty(jsonOne.get("radius").toString())){
    		    o.setRadius(Double.parseDouble(jsonOne.get("radius").toString()));
            }
    		dataList.add(o);
    	}
    	try {
			this.packDataMonitorService.saveEfenceInfo(dataList);
		} catch (DaoException e) {
			logger.error("保存电子围栏信息出错:",e);
		}
        return null;
    }
    
    @RequestMapping(value = "/updateProductionDate.mvc")
    @ResponseBody
    public Map<String, Object> updateProductionDate(TtPack t, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(StringUtils.isNotBlank(t.getProductionDateStr())){
                t.setProductionDate(f.parse(t.getProductionDateStr()));
            }
            t.setUpdateDate(new Date());
            String currentUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
            t.setUpdateUser(currentUser);
            if(this.packDataMonitorService.updateRecord(t)){
                dataMap.put("msg", "SUCCESS");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    @RequestMapping(value = "/saveArea.mvc")
    @ResponseBody
    public Map<String, Object> updateArea(TtPack t, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            t.setUpdateDate(new Date());
            String currentUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
            t.setUpdateUser(currentUser);
            if(this.packDataMonitorService.updateRecord(t)){
                dataMap.put("msg", "SUCCESS");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataMap;
    }

    @RequestMapping(value = "/getPackCode.mvc")
    @ResponseBody
    public Map<String, Object> getPackCode() {
        try {
            Map<String, Object> map = this.packDataMonitorService.getPackCode();
            return map;
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return null;
    }
    
}
